package com.gombe.credit.app.ui.activity

import android.annotation.SuppressLint
import android.os.CountDownTimer
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.databinding.ActGombeCreditUserChatBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditUserChat
import com.gombe.credit.app.ui.presenter.GombeCreditChatPresenter
import com.gombe.credit.app.ui.view.IGombeCreditChat
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.decoration.LinearSpacingItemDecoration
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.app.weight.font.LexendMediumEditText
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject

/**
 * 在线客服
 */
class ActGombeCreditUserChat: CommonActivity(), IGombeCreditChat {
    lateinit var binding: ActGombeCreditUserChatBinding
    private var presenter: GombeCreditChatPresenter? = null
    private var chatPage = 1

    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 10

    private var chatAdapter: AdapterGombeCreditUserChat? = null
    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditUserChatBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        binding.chatTitleBar.setPadding(0, GombeCreditTitleBarUtil.getStatusBarHeight(), 0, 0)
        binding.chatRefreshLayout.setColorSchemeResources(R.color.theme, R.color.purple_500)
        initGombeCreditChatListView()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initGombeCreditListener() {
        //返回
        binding.chatBack.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                finish()
            }
        })
        //内容输入框
        binding.chatEdit.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    onGombeCreditChatListViewScrollToLastItem()
                }
            }
            override fun onCompleteAction(v: View?, remark: String?) {
            }
        })
        //发送
        binding.chatSend.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val text = takeGombeCreditChatText()
                if (text.isEmpty()){
                    return
                }
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_CUSTOMER_CHAT_SEND,text)
                presenter?.sendGombeCreditCustomerChatMsgAction(text)
            }
        })
        binding.chatRefreshLayout.setOnClickListener {
            onHideSoftInput()
            binding.chatEdit.clearFocus()
        }
        //加载
        binding.chatRefreshLayout.setOnRefreshListener {
            chatPage++
            presenter?.loadGombeCreditCustomerChatRecordAction(chatPage)
        }
    }

    override fun takeGombeCreditData() {
        if (presenter == null){
            presenter = GombeCreditChatPresenter(this)
        }
        showGombeCreditLoading()
        presenter?.loadGombeCreditCustomerChatRecordAction(chatPage)
    }

    /**
     * 初始化权限列表
     */
    private fun initGombeCreditChatListView(){
        binding.chatListView.isNestedScrollingEnabled = false
        val topDecoration = GombeCreditDensityUtil.dp2px(16f)
        binding.chatListView.addItemDecoration(LinearSpacingItemDecoration(0, 0,topDecoration,topDecoration))
        binding.chatListView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        chatAdapter = AdapterGombeCreditUserChat(binding.chatListView)
        binding.chatListView.adapter = chatAdapter
        binding.chatListView.itemAnimator = DefaultItemAnimator()
        chatAdapter?.setChatGuessItemClickListener(object : AdapterGombeCreditUserChat.IChatGuessClickListener{
            override fun onGuessItemClick(text: String) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_CUSTOMER_CHAT_SEND,text)
                presenter?.sendGombeCreditCustomerChatMsgAction(text)
            }
        })
    }

    /**
     * 设置会话记录列表
     */
    override fun showGombeCreditChatRecordList(recordList: ArrayList<JSONObject>) {
        //第一页
        if (chatPage == 1){
            chatAdapter?.data = recordList
            onGombeCreditFormatLocalChat()
            onGombeCreditChatListViewScrollToLastItem()
            return
        }
        //没有更多数据
        if (recordList.size == 0){
            chatPage -= 1
        }

        //排除相同会话信息
        val idSet = HashSet<String>()
        chatAdapter?.let {
            for (item in it.data){
                val id = item.optString("id")
                if (!idSet.contains(id)){
                    idSet.add(id)
                }
            }

            val oldList = arrayListOf<JSONObject>()
            for (item in recordList){
                val id = item.optString("id")
                if (!idSet.contains(id)){
                    oldList.add(item)
                }
            }
            it.addNewData(oldList)
        }
    }

    /**
     * 定时5秒更新会话信息列表
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun showGombeCreditChatUpdaeRecordList(recordList: ArrayList<JSONObject>) {
        //排除相同会话信息
        val idSet = HashSet<String>()
        chatAdapter?.let {
            for (item in it.data){
                val id = item.optString("id")
                if (!idSet.contains(id)){
                    idSet.add(id)
                }
            }

            val newList = arrayListOf<JSONObject>()
            for (item in recordList){
                val id = item.optString("id")
                if (!idSet.contains(id)){
                    newList.add(item)
                }
            }
            if (newList.size > 0){
                it.addMoreData(newList)
                onGombeCreditChatListViewScrollToLastItem()

                //获取列表最后一条消息
                val lastItem = it.lastItem
                lastItem?.let {  item ->
                    //最后一条信息不是发送类型，需要停在倒计时，并刷新列表
                    if (item.optString("itemType") != "itemSend"){
                        if (countdownTimer != null){
                            countdownTimer?.cancel()
                            countdownTimer = null
                        }
                        it.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    /**
     * 手动添加本地信息规则
     * 添加欢迎提示语： 会话记录为空 || 最后一条消息时间已超过5分钟
     * Guess ： 会话记录为空 || 最后一条消息时间已超过10分钟
     */
    private fun onGombeCreditFormatLocalChat(){
        val chatLength = chatAdapter?.itemCount
        if (chatLength == 0){
            //手动添加一条欢迎信息
            insertGombeCreditLocalWelcomeItem()
            //手动添加一条Guess信息
            insertGombeCreditLocalGuessItem()
            return
        }
        //上一次会话时间戳
        val chatLastTime = GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_CHAT_LAST_TIME)
        if (chatLastTime.isEmpty()){//重新登录 || 换设备登录  没有上一次会话时间记录  需要默认添加
            //手动添加一条欢迎信息
            insertGombeCreditLocalWelcomeItem()
            //手动添加一条Guess信息
            insertGombeCreditLocalGuessItem()
            return
        }

        //上次会话时间 > 5分钟
        if (System.currentTimeMillis() - chatLastTime.toLong() > 5 * 60 * 1000){
            //手动添加一条欢迎信息
            insertGombeCreditLocalWelcomeItem()
        }

        //上次会话时间 > 10分钟
        if (System.currentTimeMillis() - chatLastTime.toLong() > 10 * 60 * 1000){
            //手动添加一条Guess信息
            insertGombeCreditLocalGuessItem()
        }
    }

    /**
     * 添加一条欢迎提示本地信息
     */
    private fun insertGombeCreditLocalWelcomeItem(){
        val item = JSONObject()
        item.put("id",System.currentTimeMillis())
        item.put("itemType","itemReceived")
        item.put("talkInfo",getString(R.string.gombe_credit_user_chat_reminder))
        item.put("createTimeStamp",System.currentTimeMillis())
        insertGombeCreditNewChat(item)
    }

    /**
     * 添加一条Guess本地信息
     */
    private fun insertGombeCreditLocalGuessItem(){
        val item = JSONObject()
        item.put("id",System.currentTimeMillis())
        item.put("itemType","itemGuess")
        item.put("talkInfo",getString(R.string.gombe_credit_user_chat_guess))
        item.put("createTimeStamp",System.currentTimeMillis())
        insertGombeCreditNewChat(item)
    }

    /**
     * 添加一条新消息
     */
    override fun insertGombeCreditNewChat(item: JSONObject) {
        //插入新消息前，最后一条消息类型为 “itemGuess”，需要移除后再添加最新信息
        val lastItem = chatAdapter?.lastItem
        lastItem?.let {
            if (it.optString("itemType") == "itemGuess"){
                chatAdapter?.removeItem(it)
            }
        }
        chatAdapter?.addLastItem(item)
        onGombeCreditChatListViewScrollToLastItem()
    }

    /**
     * 会话列表滑动到最底部
     */
    private fun onGombeCreditChatListViewScrollToLastItem(){
        chatAdapter?.let {
            binding.chatListView.post {
                binding.chatListView.scrollToPosition(it.itemCount - 1)
            }
        }
    }

    /**
     * 发送消息成功
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun showGombeCreditSendSuccess() {
        binding.chatEdit.setText("")
        chatAdapter?.notifyDataSetChanged()
        //获取列表最后一条消息
        val lastItem = chatAdapter?.lastItem
        lastItem?.let {  item ->
            if (item.optString("itemType") == "itemSend"){
                val createTimeStamp = item.optString("createTimeStamp","0")
                val intervalTime = (System.currentTimeMillis() - createTimeStamp.toLong()) / 1000
                if (intervalTime <= 10){
                    countdown = (10 - intervalTime).toInt()
                    startCountdownTimer()
                }
            }
        }
    }

    /**
     * 获取发送的内容
     */
    private fun takeGombeCreditChatText(): String{
        return binding.chatEdit.text.toString().trim()
    }

    /**
     * 更新最后一条发送的消息状态
     */
    private fun notifyLastItemState(){
        //获取列表最后一条消息
        chatAdapter?.let { adapter ->
            val lastItem = adapter.lastItem
            lastItem?.let {  item ->
                if (item.optString("itemType") == "itemSend"){
                    adapter.notifyItemChanged(adapter.itemCount - 1,"update-state")
                }
            }
        }
    }

    /**
     * 最后一条发送的信息 发送时间超过10秒
     */
    private fun notifyLastItemStateFinish(){
        notifyLastItemState()
        onGombeCreditChatListViewScrollToLastItem()
    }

    /**
     * 启动倒计时
     */
    private fun startCountdownTimer() {
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        //随机 10秒 等待时长
        countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: ActGombeCreditUserChat, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.notifyLastItemState()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.notifyLastItemStateFinish()
        }
    }

    override fun hideGombeCreditLoading() {
        super.hideGombeCreditLoading()
        binding.chatRefreshLayout.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_CUSTOMER_CHAT_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        //记录上次会话时间戳
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_CHAT_LAST_TIME,"${System.currentTimeMillis()}")
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_CUSTOMER_CHAT_END)
        presenter?.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}